package com.umpay.privi.util;

import java.io.IOException;
import java.io.InputStream;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *@author: liubin
 *@date：2016-8-17 下午2:46:10
 *@version 1.0
 */
public class EhcacheUtil
{
	private static Logger imlog = LoggerFactory.getLogger(EhcacheUtil.class);
	private static CacheManager cacheManager;
	private static String filename = "priviPlat_ehcache.xml";
	/** 参数校验规则缓存 */
	public static String CACHE_NAME_RULE = "checkRule";

	static
	{
		load();
	}

	public static Cache getCache(String cacheName, Class<?> clazz) throws CacheException
	{
		if (cacheManager == null)
		{
			load();
		}
		return cacheManager.getCache(cacheName);
	}

	private static void load()
	{
		imlog.info("load Ehcache");
		// JarFile earFile = null;
		// JarEntry jarEntry = null;
		InputStream in = null;
		try
		{
			// URL url =
			// EhcacheUtil.class.getClassLoader().getResource(filename);
			// String path = URLDecoder.decode(url.getPath());
			// int index = path.indexOf("!/");
			// if(index != -1){
			// path = path.substring(0, index);
			// earFile = new JarFile(path.substring(path.indexOf("/")));
			// jarEntry = earFile.getJarEntry(filename);
			// in = earFile.getInputStream(jarEntry);
			in = EhcacheUtil.class.getClassLoader().getResourceAsStream(filename);
			cacheManager = CacheManager.create(in);
			// }
		}
		catch (Exception e)
		{
			imlog.error("获取ehcache配置信息失败", e);
		}
		finally
		{
			if (in != null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					imlog.error("释放ehcache配置文件资源失败!", e);
				}
				in = null;
			}
		}
	}
}
